/*
 * Created by JFormDesigner on Wed Mar 06 11:22:48 CST 2019
 */

package com.n9.qqonline.sales.view;

import com.n9.component.table.AnnotationTableModel;
import com.n9.qqonline.sales.entity.Config;
import com.n9.qqonline.sales.service.FormService;
import com.n9.qqonline.sales.service.MsgContenUtils;
import com.n9.qqonline.sales.vo.BuyMsgVo;
import com.n9.qqonline.sales.vo.QqVo;
import com.n9.util.StringUtils;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.text.html.HTMLEditorKit;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Queue;
import java.util.*;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * @author Brainrain
 */
public class MainForm extends JFrame implements ActionListener {
    private AnnotationTableModel<QqVo> qqTableModel;

    private static MainForm me = new MainForm();
    private BuyMsgVo currentMsg;
    private Queue<BuyMsgVo> msgVos = new ConcurrentLinkedQueue<>();
    private int maxMsgCount = 30;

    private MainForm() {
        initComponents();
    }

    public static MainForm instance() {
        return me;
    }

    private void thisWindowClosed(WindowEvent e) {
        System.exit(-1);
    }

    private void initComponents() {
        // JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
        tabbedPane1 = new JTabbedPane();
        processPanel = new JPanel();
        leftPanel = new JPanel();
        panel10 = new JPanel();
        startBtn = new JButton();
        updateKeyWordsBtn = new JButton();
        button1 = new JButton();
        panel2 = new JPanel();
        scrollPane2 = new JScrollPane();
        readedMsgEditorPane = new JEditorPane();
        rightPanel = new JPanel();
        panel6 = new JPanel();
        logScrollPanel = new JScrollPane();
        logTextArea = new JTextArea();
        panel7 = new JPanel();
        panel3 = new JPanel();
        panel15 = new JPanel();
        readBtnValid = new JButton();
        readBtnInvalid = new JButton();
        totalMsgLabel = new JLabel();
        unReadMsgLabel = new JLabel();
        notesTextField = new JTextField();
        panel11 = new JPanel();
        msgContentScroll = new JScrollPane();
        msgContentTextArea = new JEditorPane();
        panel13 = new JPanel();
        searchKeyWordsTextField = new JTextField();
        msgRefreshBtn = new JButton();
        panel1 = new JPanel();
        panel12 = new JPanel();
        panel4 = new JPanel();
        scrollPane1 = new JScrollPane();
        qqTables = new JTable();
        addAccountBtn = new JButton();
        panel9 = new JPanel();
        label1 = new JLabel();
        dayText = new JTextField();
        resetBuyMsgBtn = new JButton();
        panel8 = new JPanel();
        scrollPane4 = new JScrollPane();
        buyKeyWordsTextArea = new JTextArea();
        buyKeyWordsBtn = new JButton();
        panel5 = new JPanel();
        patentFilePathTextField = new JTextField();
        setLocalPatentBtn = new JButton();
        setServerPatentBtn = new JButton();

        //======== this ========
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setTitle("sales-helper-v2.2");
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                thisWindowClosed(e);
            }
        });
        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        //======== tabbedPane1 ========
        {

            //======== processPanel ========
            {
                processPanel.setLayout(new BorderLayout());

                //======== leftPanel ========
                {
                    leftPanel.setPreferredSize(new Dimension(400, 0));
                    leftPanel.setLayout(new BorderLayout());

                    //======== panel10 ========
                    {
                        panel10.setPreferredSize(new Dimension(380, 60));
                        panel10.setMinimumSize(new Dimension(0, 0));
                        panel10.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 10));

                        //---- startBtn ----
                        startBtn.setText("\u542f\u52a8");
                        startBtn.setPreferredSize(new Dimension(90, 40));
                        panel10.add(startBtn);

                        //---- updateKeyWordsBtn ----
                        updateKeyWordsBtn.setText("\u6e05\u7a7a\u6d88\u606f");
                        updateKeyWordsBtn.setPreferredSize(new Dimension(90, 40));
                        updateKeyWordsBtn.setActionCommand("\u6e05\u7a7a\u6d88\u606f");
                        panel10.add(updateKeyWordsBtn);

                        //---- button1 ----
                        button1.setText("\u5bfc\u51fa\u6d88\u606f");
                        button1.setPreferredSize(new Dimension(90, 40));
                        panel10.add(button1);
                    }
                    leftPanel.add(panel10, BorderLayout.NORTH);

                    //======== panel2 ========
                    {
                        panel2.setLayout(new BorderLayout());

                        //======== scrollPane2 ========
                        {
                            scrollPane2.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

                            //---- readedMsgEditorPane ----
                            readedMsgEditorPane.setContentType("text/html");
                            scrollPane2.setViewportView(readedMsgEditorPane);
                        }
                        panel2.add(scrollPane2, BorderLayout.CENTER);
                    }
                    leftPanel.add(panel2, BorderLayout.CENTER);
                }
                processPanel.add(leftPanel, BorderLayout.WEST);

                //======== rightPanel ========
                {
                    rightPanel.setPreferredSize(new Dimension(650, 0));
                    rightPanel.setLayout(new BorderLayout());

                    //======== panel6 ========
                    {
                        panel6.setPreferredSize(new Dimension(0, 190));
                        panel6.setLayout(new BorderLayout());

                        //======== logScrollPanel ========
                        {
                            logScrollPanel.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
                            logScrollPanel.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

                            //---- logTextArea ----
                            logTextArea.setEnabled(false);
                            logScrollPanel.setViewportView(logTextArea);
                        }
                        panel6.add(logScrollPanel, BorderLayout.CENTER);
                    }
                    rightPanel.add(panel6, BorderLayout.SOUTH);

                    //======== panel7 ========
                    {
                        panel7.setPreferredSize(new Dimension(0, 350));
                        panel7.setLayout(new BorderLayout());

                        //======== panel3 ========
                        {
                            panel3.setPreferredSize(new Dimension(0, 60));
                            panel3.setLayout(new BorderLayout());

                            //======== panel15 ========
                            {
                                panel15.setPreferredSize(new Dimension(430, 60));
                                panel15.setLayout(new FlowLayout(FlowLayout.LEFT));

                                //---- readBtnValid ----
                                readBtnValid.setText("\u6709\u6548");
                                readBtnValid.setPreferredSize(new Dimension(100, 50));
                                readBtnValid.setActionCommand("\u6709\u6548");
                                readBtnValid.setForeground(new Color(51, 204, 0));
                                readBtnValid.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
                                panel15.add(readBtnValid);

                                //---- readBtnInvalid ----
                                readBtnInvalid.setText("\u65e0\u6548");
                                readBtnInvalid.setPreferredSize(new Dimension(75, 50));
                                readBtnInvalid.setActionCommand("\u65e0\u6548");
                                readBtnInvalid.setForeground(new Color(255, 51, 51));
                                panel15.add(readBtnInvalid);

                                //---- totalMsgLabel ----
                                totalMsgLabel.setText("text");
                                totalMsgLabel.setPreferredSize(new Dimension(100, 50));
                                totalMsgLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                                totalMsgLabel.setForeground(Color.magenta);
                                totalMsgLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
                                panel15.add(totalMsgLabel);

                                //---- unReadMsgLabel ----
                                unReadMsgLabel.setText("\u5f85\u8bfb:0\u6761");
                                unReadMsgLabel.setPreferredSize(new Dimension(100, 50));
                                unReadMsgLabel.setHorizontalAlignment(SwingConstants.RIGHT);
                                unReadMsgLabel.setForeground(new Color(255, 0, 51));
                                unReadMsgLabel.setFont(new Font("Microsoft YaHei UI", Font.BOLD, 14));
                                panel15.add(unReadMsgLabel);
                            }
                            panel3.add(panel15, BorderLayout.EAST);
                            panel3.add(notesTextField, BorderLayout.CENTER);
                        }
                        panel7.add(panel3, BorderLayout.PAGE_END);

                        //======== panel11 ========
                        {
                            panel11.setPreferredSize(new Dimension(550, 120));
                            panel11.setLayout(new BorderLayout());

                            //======== msgContentScroll ========
                            {
                                msgContentScroll.setPreferredSize(new Dimension(400, 142));
                                msgContentScroll.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);

                                //---- msgContentTextArea ----
                                msgContentTextArea.setEditable(false);
                                msgContentTextArea.setContentType("text/html");
                                msgContentTextArea.setFont(new Font("\u4eff\u5b8b", Font.PLAIN, 14));
                                msgContentScroll.setViewportView(msgContentTextArea);
                            }
                            panel11.add(msgContentScroll, BorderLayout.CENTER);
                        }
                        panel7.add(panel11, BorderLayout.CENTER);

                        //======== panel13 ========
                        {
                            panel13.setPreferredSize(new Dimension(550, 60));
                            panel13.setLayout(new FlowLayout(FlowLayout.LEFT));

                            //---- searchKeyWordsTextField ----
                            searchKeyWordsTextField.setPreferredSize(new Dimension(506, 50));
                            panel13.add(searchKeyWordsTextField);

                            //---- msgRefreshBtn ----
                            msgRefreshBtn.setText("\u641c\u7d22");
                            msgRefreshBtn.setPreferredSize(new Dimension(100, 50));
                            panel13.add(msgRefreshBtn);
                        }
                        panel7.add(panel13, BorderLayout.NORTH);
                    }
                    rightPanel.add(panel7, BorderLayout.CENTER);
                }
                processPanel.add(rightPanel, BorderLayout.CENTER);
            }
            tabbedPane1.addTab("\u6d88\u606f\u5904\u7406", processPanel);

            //======== panel1 ========
            {
                panel1.setPreferredSize(new Dimension(600, 600));
                panel1.setLayout(new BorderLayout());

                //======== panel12 ========
                {
                    panel12.setPreferredSize(new Dimension(600, 500));
                    panel12.setLayout(new FlowLayout(FlowLayout.LEFT));

                    //======== panel4 ========
                    {
                        panel4.setPreferredSize(new Dimension(650, 250));
                        panel4.setLayout(new FlowLayout(FlowLayout.LEFT));

                        //======== scrollPane1 ========
                        {
                            scrollPane1.setPreferredSize(new Dimension(500, 230));

                            //---- qqTables ----
                            qqTables.setPreferredScrollableViewportSize(new Dimension(300, 350));
                            qqTables.setPreferredSize(new Dimension(350, 350));
                            scrollPane1.setViewportView(qqTables);
                        }
                        panel4.add(scrollPane1);

                        //---- addAccountBtn ----
                        addAccountBtn.setText("\u8bbe\u7f6e\u8d26\u53f7");
                        addAccountBtn.setPreferredSize(new Dimension(100, 60));
                        panel4.add(addAccountBtn);
                    }
                    panel12.add(panel4);

                    //======== panel9 ========
                    {
                        panel9.setMaximumSize(new Dimension(650, 100));
                        panel9.setMinimumSize(new Dimension(650, 100));
                        panel9.setPreferredSize(new Dimension(650, 100));
                        panel9.setLayout(new FlowLayout(FlowLayout.LEFT));

                        //---- label1 ----
                        label1.setText("\u65e5\u671f:");
                        label1.setMaximumSize(new Dimension(100, 40));
                        label1.setMinimumSize(new Dimension(100, 40));
                        label1.setPreferredSize(new Dimension(100, 40));
                        panel9.add(label1);

                        //---- dayText ----
                        dayText.setMinimumSize(new Dimension(150, 50));
                        dayText.setMaximumSize(new Dimension(150, 50));
                        dayText.setPreferredSize(new Dimension(150, 50));
                        panel9.add(dayText);

                        //---- resetBuyMsgBtn ----
                        resetBuyMsgBtn.setText("\u590d\u4f4d\u6709\u6548\u6d88\u606f");
                        resetBuyMsgBtn.setMaximumSize(new Dimension(100, 40));
                        resetBuyMsgBtn.setMinimumSize(new Dimension(100, 40));
                        resetBuyMsgBtn.setPreferredSize(new Dimension(100, 40));
                        panel9.add(resetBuyMsgBtn);
                    }
                    panel12.add(panel9);

                    //======== panel8 ========
                    {
                        panel8.setPreferredSize(new Dimension(650, 120));
                        panel8.setLayout(new FlowLayout(FlowLayout.LEFT));

                        //======== scrollPane4 ========
                        {
                            scrollPane4.setPreferredSize(new Dimension(500, 110));

                            //---- buyKeyWordsTextArea ----
                            buyKeyWordsTextArea.setPreferredSize(new Dimension(280, 110));
                            buyKeyWordsTextArea.setLineWrap(true);
                            scrollPane4.setViewportView(buyKeyWordsTextArea);
                        }
                        panel8.add(scrollPane4);

                        //---- buyKeyWordsBtn ----
                        buyKeyWordsBtn.setText("\u6c42\u8d2d\u5173\u952e\u8bcd");
                        buyKeyWordsBtn.setPreferredSize(new Dimension(100, 60));
                        panel8.add(buyKeyWordsBtn);
                    }
                    panel12.add(panel8);

                    //======== panel5 ========
                    {
                        panel5.setPreferredSize(new Dimension(750, 70));
                        panel5.setLayout(new FlowLayout(FlowLayout.LEFT));

                        //---- patentFilePathTextField ----
                        patentFilePathTextField.setPreferredSize(new Dimension(500, 60));
                        patentFilePathTextField.setEditable(false);
                        panel5.add(patentFilePathTextField);

                        //---- setLocalPatentBtn ----
                        setLocalPatentBtn.setText("\u8bbe\u7f6e\u672c\u5730\u4e13\u5229");
                        setLocalPatentBtn.setPreferredSize(new Dimension(100, 60));
                        setLocalPatentBtn.setActionCommand("\u8bbe\u7f6e\u672c\u5730\u4e13\u5229");
                        panel5.add(setLocalPatentBtn);

                        //---- setServerPatentBtn ----
                        setServerPatentBtn.setText("\u8bbe\u7f6e\u8fdc\u7a0b\u4e13\u5229");
                        setServerPatentBtn.setPreferredSize(new Dimension(100, 60));
                        setServerPatentBtn.setActionCommand("\u8bbe\u7f6e\u8fdc\u7a0b\u4e13\u5229");
                        panel5.add(setServerPatentBtn);
                    }
                    panel12.add(panel5);
                }
                panel1.add(panel12, BorderLayout.CENTER);
            }
            tabbedPane1.addTab("\u8d26\u53f7\u914d\u7f6e", panel1);
        }
        contentPane.add(tabbedPane1, BorderLayout.CENTER);
        pack();
        setLocationRelativeTo(getOwner());
        // JFormDesigner - End of component initialization  //GEN-END:initComponents
        this.setSize(1200, 800);
        this.setLocationRelativeTo(null);
//        this.setResizable(false);

        qqTableModel = new AnnotationTableModel<QqVo>(QqVo.class, qqTables){
            @Override
            public void updateRow(QqVo qqVo) {
                Iterator<QqVo> it = rows.iterator();
                int i = 0;
                while(it.hasNext()) {
                    QqVo rowQq = it.next();
                    if (Objects.equals(rowQq.getUin(), qqVo.getUin())) {
                        rowQq.setGroupCount(qqVo.getGroupCount());
                        rowQq.setNick(qqVo.getNick());
                        this.fireTableRowsUpdated(i, i);
                        break;
                    }
                    i++;
                }

            }
        };
        DefaultTableCellRenderer tcr = new DefaultTableCellRenderer();
        tcr.setHorizontalAlignment(SwingConstants.CENTER);
        tcr.setBackground(Color.decode("#eeeeee"));
        tcr.setForeground(Color.decode("#888888"));
        qqTables.getColumnModel().getColumn(0).setCellRenderer(tcr);

        msgRefreshBtn.addActionListener(this);
        buyKeyWordsBtn.addActionListener(this);
        setLocalPatentBtn.addActionListener(this);
        setServerPatentBtn.addActionListener(this);
        startBtn.addActionListener(this);
        readBtnInvalid.addActionListener(this);
        readBtnValid.addActionListener(this);
        resetBuyMsgBtn.addActionListener(this);
        updateKeyWordsBtn.addActionListener(this);
        addAccountBtn.addActionListener(this);

        msgContentTextArea.setEditorKit(new HTMLEditorKit());
        readedMsgEditorPane.setEditorKit(new HTMLEditorKit());
        readedMsgEditorPane.setText("");
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        new FormService().doActionPerformed(e);
    }

    public String getRestDay() {
        return dayText.getText().trim();
    }

    /**
     * 设置专利清单路径
     * @param patentFilePath
     */
    public void setPatentFilePath(String patentFilePath) {
        this.patentFilePathTextField.setText(patentFilePath);
    }

    public String getPatentFilePath() {
        return patentFilePathTextField.getText().trim();
    }

    /**
     * 获取日志控件
     * @return
     */
    public JTextArea getLogTextArea() {
        return this.logTextArea;
    }

    /**
     * 获取QQ表格模型
     * @return
     */
    public AnnotationTableModel<QqVo> getQqTableModel() {
        return this.qqTableModel;
    }

    /**
     * 求购信息关键词
     * @return
     */
    public String getBuyKeyWords() {
        return this.buyKeyWordsTextArea.getText().trim();
    }

    /**
     * 设置关键词
     * @param buyKeyWords
     * @param searchKeyWords
     */
    public void setKeyWords(String buyKeyWords, String searchKeyWords) {
        SwingUtilities.invokeLater(()->{
            this.buyKeyWordsTextArea.setText(buyKeyWords);
            this.searchKeyWordsTextField.setText(searchKeyWords);
        });
    }

    /**
     * 显示求购信息
     * @param buyMsgVo
     */
    public void viewBuyMsg(BuyMsgVo buyMsgVo) {
        currentMsg = buyMsgVo;
        String content = "";
        String notes = "";

        String[] searchKeyWords = null;
        String searchKeyWordStr = getSearchKeyWordStr();
        if (Objects.nonNull(buyMsgVo)) {
            if (StringUtils.hasText(searchKeyWordStr)) {
                searchKeyWords = getSearchKeyWordStr().split(Config.SEPARATOR_REGEX);
            }
            content = MsgContenUtils.getStyleContent(buyMsgVo, searchKeyWords);
            notes += Objects.isNull(buyMsgVo.getNotes()) ? "" : buyMsgVo.getNotes();
        }
        msgContentTextArea.setText(content);
        msgContentTextArea.setCaretPosition(0);
        notesTextField.setText(notes);
    }

    public String getMsgNotes() {
        return notesTextField.getText().trim();
    }

    /**
     * 设置未读消息数量
     * @param unReadCount
     */
    public void setUnReadMsgCount(long totalCount, long unReadCount) {
        SwingUtilities.invokeLater(
                ()->{
                    unReadMsgLabel.setText(String.format("待读:%d条", unReadCount));
                    totalMsgLabel.setText(String.format("总共:%d条", totalCount));
                }
        );
    }

    public void setReadedMsg(List<BuyMsgVo> msgs) {
        if (Objects.isNull(msgs)) {
            return;
        }
        msgs.forEach(msg->{
            if (msgVos.size() > maxMsgCount) {
                msgVos.poll();
            }
            msgVos.add(msg);
        });
        viewReadMsg();
    }

    private void viewReadMsg() {
        Map<String, Object> map = new HashMap<>(0);
        map.put("buyMsgs", msgVos);
        String buyMsgHistoryStr = FreemarkerUtils.render("buyMsgHistory.ftl", map);
        readedMsgEditorPane.setText(buyMsgHistoryStr);
    }

    public void addReadedMsg(BuyMsgVo msg) {
        if (Objects.isNull(msg)) {
            return;
        }
        if (msgVos.size() > maxMsgCount) {
            msgVos.poll();
        }
        msgVos.add(msg);
        viewReadMsg();
    }

    public String getSearchKeyWordStr() {
        return this.searchKeyWordsTextField.getText().trim();
    }

    public void setMsgNotes(String notes) {
        SwingUtilities.invokeLater(()-> notesTextField.setText(notes));
    }
    public BuyMsgVo getCurrentMsg() {
        return this.currentMsg;
    }

    public JButton getAddAccountBtn() {
        return this.addAccountBtn;
    }
    public JButton getStartBtn() {
        return this.startBtn;
    }
    public JScrollPane getLogScrollPanel() {
        return this.logScrollPanel;
    }


    // JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
    private JTabbedPane tabbedPane1;
    private JPanel processPanel;
    private JPanel leftPanel;
    private JPanel panel10;
    private JButton startBtn;
    private JButton updateKeyWordsBtn;
    private JButton button1;
    private JPanel panel2;
    private JScrollPane scrollPane2;
    private JEditorPane readedMsgEditorPane;
    private JPanel rightPanel;
    private JPanel panel6;
    private JScrollPane logScrollPanel;
    private JTextArea logTextArea;
    private JPanel panel7;
    private JPanel panel3;
    private JPanel panel15;
    private JButton readBtnValid;
    private JButton readBtnInvalid;
    private JLabel totalMsgLabel;
    private JLabel unReadMsgLabel;
    private JTextField notesTextField;
    private JPanel panel11;
    private JScrollPane msgContentScroll;
    private JEditorPane msgContentTextArea;
    private JPanel panel13;
    private JTextField searchKeyWordsTextField;
    private JButton msgRefreshBtn;
    private JPanel panel1;
    private JPanel panel12;
    private JPanel panel4;
    private JScrollPane scrollPane1;
    private JTable qqTables;
    private JButton addAccountBtn;
    private JPanel panel9;
    private JLabel label1;
    private JTextField dayText;
    private JButton resetBuyMsgBtn;
    private JPanel panel8;
    private JScrollPane scrollPane4;
    private JTextArea buyKeyWordsTextArea;
    private JButton buyKeyWordsBtn;
    private JPanel panel5;
    private JTextField patentFilePathTextField;
    private JButton setLocalPatentBtn;
    private JButton setServerPatentBtn;
    // JFormDesigner - End of variables declaration  //GEN-END:variables

}
